//
//  YuYueViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-6-6.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "YuYueViewController.h"
#import "NSDate+RYAdditions.h"
#import "NYMemberCenterDataManager.h"
#import "YuYueListViewController.h"
#import "JSON.h"

#define kMoneyUnit 10000.f

@interface YuYueViewController ()

@end

@implementation YuYueViewController

@synthesize productDetail;
@synthesize nameLabel,shouyilvLabel,datePicker,commitButton,moneyField,dateLabel;
@synthesize minLabel,maxLabel,addLabel;
@synthesize isEditYuyue;
@synthesize unitLabel;

- (IBAction)commitButtonClicked:(id)sender
{
    NSString *validString = [self checkValid];
    if(validString)
    {
        [[RYHUDManager sharedManager] showWithMessage:validString customView:nil hideDelay:2.f];
    }
    else
    {
        NSString *stringDate = [NSDate dateToStringByFormat:@"yyyy-MM-dd" date:self.datePicker.date];
        stringDate = @"";
        NSString *suburl = nil;
        
        NSNumberFormatter *formatter = [NSNumberFormatter new];
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
        NSNumber *moneyNumber = [formatter numberFromString:self.moneyField.text];
        CGFloat moneyFloat = moneyNumber.floatValue;
        if(self.productDetail.mixsingle > kMoneyUnit)
            moneyFloat = moneyFloat*kMoneyUnit;
        [formatter release];
        
        if(self.isEditYuyue)
        {
            suburl = [NSString stringWithFormat:kEditYuyueProductUrl,@"jsonp",stringDate,(NSInteger)moneyFloat,@"",@"",productDetail.sf_opportunity_id];
            suburl = [suburl stringByAppendingString:@"app000044"];
        }
        else
        {
            suburl = [NSString stringWithFormat:kYuyueProductUrl,@"jsonp",stringDate,productDetail.productbooking_id,[NYMemberCenterDataManager sharedManager].loginMember.accountId,(NSInteger)moneyFloat,@""];
            suburl = [suburl stringByAppendingString:@"app000036"];
        }
        NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
    }
}

- (NSString *)checkValid
{
    NSNumberFormatter *formatter = [NSNumberFormatter new];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *moneyNumber = [formatter numberFromString:self.moneyField.text];
    CGFloat moneyFloat = moneyNumber.floatValue;
    if(self.productDetail.mixsingle > kMoneyUnit)
        moneyFloat = moneyFloat*kMoneyUnit;
    [formatter release];
    //金额-  类型：数字 长度：1-6 默认值：根据最低投资金额默认 注：单位为万元，输入值需根据最低投资金额和单笔增加金额控制
    //返回的最大金额max_single__c=0时，表示最大金额无上限，客户端不需要做最大值判断
    //日期- 类型：（YYYYMMDD）长度：8-8 默认值：当前日期 注：输入值需根据开始签约日期和结束签约日期控制
    if(moneyField.text.length < 1)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"预约金额"];
    else if(moneyField.text.length > 6)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000002E"],@"预约金额"];
    else if(moneyFloat < self.productDetail.mixsingle)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000003E"],@"预约金额"];
    else if((NSInteger)(moneyFloat-self.productDetail.mixsingle)%self.productDetail.max_single_add__c != 0)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000003E"],@"预约金额"];
    else if(self.productDetail.max_single__c == 0)
        return nil;
    else if(moneyFloat > self.productDetail.max_single__c)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000003E"],@"预约金额"];
    return nil;
}

- (void)moneyFieldChangedWithNotification:(NSNotification *)notification
{
    /**
     你根据用户输入的金额判断是在那个区间  productyieldlist
     {
     "expected_yield": "8",
     "expected_yield_num": 8,
     "high_limit": 3000000,
     "high_limit_with__c": "N",
     "lower_limit": 1000000,
     "lower_limit_with__c": "Y"
     }
     */
    
//    NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"8",@"expected_yield",
//                           [NSNumber numberWithInt:8],@"expected_yield_num",
//                           [NSNumber numberWithInt:3000000],@"high_limit",
//                           @"N",@"high_limit_with__c",
//                           [NSNumber numberWithInt:1000000],@"lower_limit",
//                           @"Y",@"lower_limit_with__c",nil];
//    NSDictionary *dict2 = [NSDictionary dictionaryWithObjectsAndKeys:@"9",@"expected_yield",
//                           [NSNumber numberWithInt:9],@"expected_yield_num",
//                           [NSNumber numberWithInt:5000000],@"high_limit",
//                           @"N",@"high_limit_with__c",
//                           [NSNumber numberWithInt:3000000],@"lower_limit",
//                           @"Y",@"lower_limit_with__c",nil];
//    NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"10",@"expected_yield",
//                           [NSNumber numberWithInt:10],@"expected_yield_num",
//                           @"",@"high_limit",
//                           @"N",@"high_limit_with__c",
//                           [NSNumber numberWithInt:5000000],@"lower_limit",
//                           @"Y",@"lower_limit_with__c",nil];
//    
//    self.productDetail.productyieldlist = [NSArray arrayWithObjects:dict1,dict2,dict3, nil];
    if(self.productDetail.productyieldlist.count != 0)
    {
        CGFloat money = [moneyField.text floatValue]*kMoneyUnit;
        
        for(NSDictionary *dict in self.productDetail.productyieldlist)
        {
            CGFloat minValue = [[dict objectForKey:@"lower_limit"] floatValue];
            CGFloat maxValue = [[dict objectForKey:@"high_limit"] floatValue];
            if(maxValue == 0)
                maxValue = NSIntegerMax;
            BOOL containLeft = [[dict objectForKey:@"lower_limit_with__c"] isEqualToString:@"Y"];
            BOOL containRight = [[dict objectForKey:@"high_limit_with__c"] isEqualToString:@"Y"];
            
            if(money > minValue && money < maxValue)
            {
                self.shouyilvLabel.text = [NSString stringWithFormat:@"%@%%",[dict objectForKey:@"expected_yield"]];
            }
            else
            {
                if(containLeft)
                {
                    if(money == minValue)
                        self.shouyilvLabel.text = [NSString stringWithFormat:@"%@%%",[dict objectForKey:@"expected_yield"]];
                }
                if(containRight)
                {
                    if(money == maxValue)
                        self.shouyilvLabel.text = [NSString stringWithFormat:@"%@%%",[dict objectForKey:@"expected_yield"]];
                }
            }
        }
    }
}

#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightItemTapped
{    
    NSArray *properties = [NSArray arrayWithObject:@"Call"];
    NSMutableDictionary *filterInfo = [NSMutableDictionary dictionary];
    [filterInfo setObject:properties forKey:kFilterPropertiesKey];
    [filterInfo setObject:[NSNumber numberWithInt:kLocationRight] forKey:kFilterLocationType];
    [filterInfo setObject:[NSNumber numberWithInteger:kProYuyueFilter] forKey:kFilterTypeKey];
    [[NSNotificationCenter defaultCenter] postNotificationName:kShowFilterViewNotification object:nil userInfo:filterInfo];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moneyFieldChangedWithNotification:) name:UITextFieldTextDidChangeNotification object:nil];
    if(self.isEditYuyue)
        [self setNaviTitle:@"修改预约"];
    else
        [self setNaviTitle:@"预约产品"];
    [self setLeftNaviItemWithTitle:nil imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:@"Icon_Dial"];
    
    self.nameLabel.text = self.productDetail.public_product_name;
    if(nil == self.productDetail.product_yield ||
       [self.productDetail.product_yield isEqualToString:@""])
        self.shouyilvLabel.text = @"浮动";
    else
    {
        self.shouyilvLabel.text = self.productDetail.product_yield;
    }
    
    self.minLabel.text = self.productDetail.mixsingle_view;
    self.maxLabel.text = self.productDetail.max_single_view;
    self.addLabel.text = self.productDetail.max_single_add_view;
    
    NSNumberFormatter *formatter = [NSNumberFormatter new];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // this line is important!
    
    NSString *moneyString = nil;
    if(!self.isEditYuyue)
    {
        if(self.productDetail.mixsingle < kMoneyUnit)
        {
            moneyString = [formatter stringFromNumber:[NSNumber numberWithFloat:self.productDetail.mixsingle]];
            self.unitLabel.text = @"元";
            self.moneyField.text = moneyString;
        }
        else
        {
            moneyString = [formatter stringFromNumber:[NSNumber numberWithFloat:self.productDetail.mixsingle/kMoneyUnit]];
            self.unitLabel.text = @"万元";
            self.moneyField.text = moneyString;
        }
    }
    else
    {
        if([self.productDetail.amount floatValue] < kMoneyUnit)
        {
            moneyString = [formatter stringFromNumber:[NSNumber numberWithFloat:[self.productDetail.amount floatValue]]];
            self.unitLabel.text = @"元";
            self.moneyField.text = moneyString;
        }
        else
        {
            moneyString = [formatter stringFromNumber:[NSNumber numberWithFloat:[self.productDetail.amount floatValue]/kMoneyUnit]];
            self.unitLabel.text = @"万元";
            self.moneyField.text = moneyString;
        }
    }
    [formatter release];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        self.view = nil;
        self.nameLabel = nil;
        self.shouyilvLabel = nil;
        self.datePicker = nil;
        self.commitButton = nil;
        self.moneyField = nil;
        self.dateLabel = nil;
        self.minLabel = nil;
        self.maxLabel = nil;
        self.addLabel = nil;
        self.unitLabel = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.nameLabel = nil;
    self.shouyilvLabel = nil;
    self.datePicker = nil;
    self.commitButton = nil;
    self.moneyField = nil;
    self.dateLabel = nil;
    self.minLabel = nil;
    self.maxLabel = nil;
    self.addLabel = nil;
    self.unitLabel = nil;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [unitLabel release];
    [minLabel release];
    [maxLabel release];
    [addLabel release];
    [dateLabel release];
    [moneyField release];
    [nameLabel release];
    [shouyilvLabel release];
    [datePicker release];
    [commitButton release];
    [productDetail release];
    [super dealloc];
}

#pragma mark - UIResponder methods
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.moneyField resignFirstResponder];
    NSString *validString = [self checkValid];
    if(validString)
    {
        [[RYHUDManager sharedManager] showWithMessage:validString customView:nil hideDelay:2.f];
    }
}


- (IBAction)datePickerValueChanged
{
    NSString *stringDate = [NSDate dateToStringByFormat:@"yyyyMMdd" date:self.datePicker.date];
    self.dateLabel.text = stringDate;
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshYuyueProductsNotification object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:kRefreshOnlneProductsNotification object:nil];
        UIAlertView *av = [[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"您已成功预约产品 %@",self.productDetail.public_product_name] message:nil delegate:self cancelButtonTitle:@"我的预约" otherButtonTitles:@"继续浏览", nil] autorelease];
        [av show];
    }
    else
    {
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - UIAlertViewDelegate methods
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        YuYueListViewController *yylvc = [[YuYueListViewController alloc] init];
        yylvc.isFromEdit = YES;
        yylvc.yuyueEnter = kYuyueAlertEnter;
        [self.navigationController pushViewController:yylvc animated:YES];
        [yylvc release];
    }
    else if(buttonIndex == 1)
    {
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    }
}
@end
